<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>跨浏览器方式</title>
		<script type="text/javascript" src="getXml.js"></script>
	</head>

	<body>
	</body>
	<div>在dom3级XPath规范定义的类型中重要的两个类型是XPathEvaluator和 XPathResult。其中,XPathEvaluator用于特定上下文对XPath表达式求值
	</div>
	<script>
		var xmlStr = '<root><b><user id="5">zhangsan</user><user id="4">lisi</user></b></root>';
		var xmlDom = getXMLDOM(xmlStr);

		//两种方式创建XPathResult

		//单一节点 w3c XPAth 下边从1开始
		/*	var eva = new XPathEvaluator();
			var result = eva.evaluate('//user[1]',xmlDom,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null);
			 if(result!==null){
			 	alert(serializerXml(result.singleNodeValue));
			 }*/

		var result = xmlDom.evaluate('//user[1]', xmlDom, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
		if(result !== null) {
			alert(serializerXml(result.singleNodeValue));
		}

		//节点集合
		var results = xmlDom.evaluate('//user', xmlDom, null,
			XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
		var nodes = [];
		if(results !== null) {
			while((node = results.iterateNext()) !== null) {
				nodes.push(node);
			}
		}

		alert(serializerXml(nodes[0]));

		//XPath跨浏览器兼容
		/*如果要做W3C和IE的跨浏览器兼容，我们要思考几个问题：
		1.如果传递一个节点的下标，IE是从0开始计算，W3C从1开始计算，可以通过传递获取下标进行增1减1的操作来进行。
		2.独有的功能放弃，为了保证跨浏览器。
		3.只获取单一节点和节点列表即可，基本可以完成所有的操作。*/

		//跨浏览器获取单一节点
		function selectSingleNode(xmlDom, xpath) {
			var node = null;

			if(typeof xmlDom.evaluate != 'undefined') { //w3c
				var patten = /\[(\d+)\]/g; //获取数值
				var flag = xpath.match(patten);
				var num = 0;
				if(flag !== null) {
					num = parseInt(RegExp.$1) + 1; //w3c下标1表示[0]
					xpath = xpath.replace(patten, '[' + num + ']');
				}
				var result = xmlDom.evaluate(xpath, xmlDom, null,
					XPathResult.FIRST_ORDERED_NODE_TYPE, null);
				if(result !== null) {
					node = result.singleNodeValue;
				}
			} else if(typeof xmlDom.selectSingleNode != 'undefined') { //ie
				node = xmlDom.selectSingleNode(xpath);
			}

			return node;
		}
		//验证
		var xmldomNode = selectSingleNode(xmlDom, 'root/b/user[1]')
		alert(serializerXml(xmldomNode));
		
		

		//跨浏览器节点集合
		function selectNodes(xmlDom, xpath) {
			var nodes = [];
			if(typeof xmlDom.evaluate != 'undefined') { //W3C
				var patten = /\[(\d+)\]/;
				var flag = xpath.match(patten);
				var num = 0;
				if(flag !== null) {
					num = parseInt(RegExp.$1) + 1;
					xpath = xpath.replace(patten, '[' + num + ']');
				}
				var result = xmlDom.evaluate(xpath, xmlDom, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
				if(result != null) {
					var node = null;
					while((node = result.iterateNext()) !== null) {
						nodes.push(node);
					}
				}
			} else if(typeof xmlDom.selectNodes != 'undefined') { //IE
				nodes = xmlDom.selectNodes(xpath);
			}

			return nodes;
		}
		
		//验证
		var nodes = selectNodes(xmlDom, 'root/b/user');
		alert(nodes.length);
		alert(serializerXml(nodes[0]));
		alert(serializerXml(nodes[1]));
		
	</script>

</html>